package com.stud.common.core.mybatis;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * 根据 ID 更新有值字段,空值数据库设置为null
 *
 * @author Stud
 * @since 2023-03-18 15:49:28
 */
public class UpdateFullById extends AbstractMethod {

    public UpdateFullById() {
        this("updateFullById");
    }

    public UpdateFullById(String name) {
        super(name);
    }

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        StringBuilder sb = new StringBuilder();
        sb.append("<script>");
        sb.append("UPDATE").append(" ").append(tableInfo.getTableName()).append(" set ");

        tableInfo.getFieldList().forEach(tableFieldInfo -> sb.append(tableFieldInfo.getColumn()).append("=#{").append(tableFieldInfo.getProperty()).append("},"));
        sb.setLength(sb.length() - 1);
        sb.append(" WHERE ").append(tableInfo.getKeyColumn()).append("=#{").append(tableInfo.getKeyProperty()).append("}");
        sb.append("</script>");

        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sb.toString(), modelClass);
        return addUpdateMappedStatement(mapperClass, modelClass, "updateFullById", sqlSource);
    }
}
